<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button
          size="mini"
          type="primary"
          @click="
            showDialog = true;
            isAdd = true;
          "
        >添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column align="center" width="200" label="角色">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="启用" prop="state">
          <!-- 自定义列表结构 -->
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" size="mini" :active-value="1" :inactive-value="0" />
            <span v-else> {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="primary" size="mini" @click="okChange(row)">确定</el-button>
              <el-button size="mini" @click="noChange(row)">取消</el-button>
            </template>

            <template v-else>
              <!-- 非编辑状态 -->
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="showdit(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="confirmDel(row.id)"
              >
                <el-button slot="reference" style="margin-left:10px ;" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>

          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height: 60px" align="middle" justify="end">
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="btnCancel">
      <!-- 表单内容 -->
      <el-form ref="roleForm" label-width="120px" :model="roleForm" :rules="rules">
        <el-form-item label="角色名字" prop="name">
          <el-input v-model="roleForm.name" style="width: 300px" size="mini" />
        </el-form-item>
        <!-- 如果不做校验,而且不做数据清空,则不需要加prop属性 -->
        <el-form-item label="启用" prop="state">
          <el-switch v-model="roleForm.state" size="mini" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width: 300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 放置权限弹层 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <!-- 放置权限数据 -->
      <el-tree
        ref="permTree"
        node-key="id"
        :data="permissionData"
        :props="{ label: 'name' }"
        show-checkbox
        check-strictly
        default-expand-all
        :default-checked-keys="permIds"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
        <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, updateRole, delRole, getRole } from '@/api/role'
import { getPermissionList, assignPerm } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      total: 0, // 数据总条数
      pageParams: {
        page: 1, // 当前显示第几页
        pagesize: 5 // 每页多少条数据
      },
      showDialog: false, // 控制弹窗是否显示
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未启用 关闭 0 打开1
      },
      rules: {
        name: [
          { required: true, message: '角色名字不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      showPermissionDialog: false, // 分配角色弹窗是否显示
      permissionData: [], // 分配角色数据列表
      currentRoleId: null, // 记录点击分配权限的id
      permIds: [] // 已选权限列表
    }
  },
  created() {
    // 数据初始化完成,调接口请求数据
    this.getRoleList()
  },
  methods: {
    // 调接口函数
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      // 请求的数据添加一个属性
      rows.forEach(item => {
        this.$set(item, 'isEdit', false)
        // 增加缓存数据
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.list = rows
      // 把总条数赋值
      this.total = total
    },
    // 当页码改变,执行该函数
    changePage(page) {
      // 修改要显示的页码
      this.pageParams.page = page
      // 重新调接口
      this.getRoleList()
    },
    btnOK() {
      this.$refs.roleForm.validate(async(isOK) => {
        if (isOK) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功!')

          // 重新调接口
          this.getRoleList()
          // 关闭弹窗
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 编辑信息
    async showdit(row) {
      // 每次显示之前先更新缓存数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
      // 展示编辑状态
      row.isEdit = true
    },
    // 确认编辑
    async okChange(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRole(row.id, row.editRow)
        // 这里把缓存里面的数据赋值给渲染页面的数据
        Object.assign(row, {
          ...row.editRow,
          isEdit: false // 退出编辑模式
        })
        this.$message.success('编辑成功！')
      } else {
        this.$message.warning('输入信息不能为空！')
      }
    },
    // 取消编辑
    noChange(row) {
      row.isEdit = false
    },
    // 删除
    async  confirmDel(id) {
      await delRole(id)
      this.$message.success('删除成功！')
      // 删除的如果是最后一个
      if (this.list.length === 1) this.pageParams.page-- // 页码减一
      // 重新渲染页面
      this.getRoleList()
    },
    // 获取分配权限数据
    async  btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRole(id)
      this.permIds = permIds
      this.permissionData = transListToTreeData(await getPermissionList(), 0)
      this.showPermissionDialog = true
    },
    // 确定分配权限按钮
    async btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        // 获取当前勾选的id组成数组
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      // 关闭弹窗
      this.showPermissionDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.role-operate {
  padding: 10px;
}
</style>
